function sendGroupMsg(data, floatingWindow) {
  if (!data.groupId || !data.groupName || !data.message) {
    log("参数异常" + JSON.stringify(data));
    return;
  }
  结束运行("QQ");
  openQqGroup(data.groupId);
  click发消息按钮(floatingWindow);
  enterMsg(data.message, floatingWindow);
  clickSendButton(floatingWindow);
  back();
  sleep(300);
  back();
  sleep(300);
}
function openQqGroup(groupId) {
  let data = "mqqapi://card/show_pslcard?src_type=internal&version=1&card_type=group&uin=" + groupId;
  app.startActivity({
    action: "android.intent.action.VIEW",
    data: data,
    packageName: "com.tencent.mobileqq",
  });
}
function click发消息按钮(floatingWindow) {
  // floatingWindow
  for (var i = 0; i < 10; i++) {
    floatingWindow.toggleFocus();
    let view = text("发消息")
      .visibleToUser(true)
      .boundsInside(0, device.height * 0.7, device.width, device.height)
      .findOne(1111);
    if (view) {
      view.click();
      sleep(300);
      return true;
    }
  }
  throw new Error("没有找到发消息按钮");
}
function enterMsg(msg, floatingWindow) {
  let view;
  for (var i = 0; i < 10; i++) {
    floatingWindow.toggleFocus();
    view = idEndsWith("input")
      .visibleToUser(true)
      .boundsInside(0, device.height * 0.3, device.width, device.height)
      .findOne(1111);
    if (view) {
      view.setText(msg);
      sleep(300);
      return true;
    }
  }
  throw new Error("设置输入框内容异常");
}
function clickSendButton() {
  for (var i = 0; i < 10; i++) {
    floatingWindow.toggleFocus();
    let view = text("发送")
      .visibleToUser(true)
      .boundsInside(0, device.height * 0.7, device.width, device.height)
      .findOne(1111);
    if (view) {
      view.click();
      sleep(300);
      return true;
    }
  }
  throw new Error("没有找到发送按钮");
}
function 结束运行(appName) {
  var packageName = getPackageName(appName);
  app.openAppSetting(packageName);
  sleep(3000);
  try {
    text("结束运行").enabled(true).className("android.widget.Button").findOne(2222).click();
    sleep(500);
  } catch (e) {}
  try {
    text("确定").className("android.widget.Button").findOne(2222).click();
    sleep(500);
  } catch (e) {}
  sleep(500);
  back();
  sleep(500);
}
module.exports = {
  sendGroupMsg: sendGroupMsg,
};
